﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using YJTShiftManagement.Utils;

namespace YJTShiftManagement.Service
{
    public class BaseService
    {

        //public static string baseUrl = "https://www.lianjieit.net/gf/";
        //public static string baseUrl = "http://192.168.1.131/gf/";
        //public static string baseUrl = "https://dvp.lianjieit.net/his_dvp/";
        public static string baseUrl = "https://testyjt.lianjieit.net/gf/";//测试
        //public static string baseUrl = "http://dvp.lianjieit.net/his_dvp/";
        #region -- 原始异步访问机制，
        //        public static async Task<HttpResult> HttpService2(string url, dynamic p)
        //        {
        //            // by wei,20200526 此处注释，因为发布后log.db 是明文存储接口地址 和 出参入参的记录，非常不安全，故发布版本注释掉此段代码
        //            //var sdb = new SqliteDb();
        //            //sdb.url = url;
        //            //sdb.param = JsonConvert.SerializeObject(p);
        //            //sdb.mac = Program.BoardID;
        //            //sdb.computer = Dns.GetHostName();
        //            // END BY WEI 20200526
        //#if DEBUG
        //            // baseUrl= "https://www.lianjieit.net/his_dvp/"; //debug wei 调试
        //#endif
        //            HttpClient httpClient = new HttpClient();
        //            httpClient.BaseAddress = new Uri(baseUrl);
        //            string json = JsonConvert.SerializeObject(p);
        //            var content = new StringContent(json);
        //            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        //            var response = httpClient.PostAsync(url, content);
        //#if DEBUG
        //            Console.WriteLine("JSON输出" + json); //debug Jack 调试json
        //#endif
        //            var httpCode = response.Result.StatusCode;
        //            if (httpCode == HttpStatusCode.OK)
        //            {

        //                var res = response.Result.Content.ReadAsStringAsync();
        //                //return await Task.Run<HttpResult>(() =>  //原有4.5框架下的代码
        //                return await Task.Factory.StartNew<HttpResult>(() =>   //4.0框架下支持的代码
        //                {
        //                    // by wei,20200526 此处注释，因为发布后log.db 是明文存储接口地址 和 出参入参的记录，非常不安全，故发布版本注释掉此段代码
        //                    //sdb.result = res.Result;
        //                    //LogHelper.AddSqliteDb(sdb);
        //                    // END BY WEI 20200526

        //#if DEBUG
        //                    Console.WriteLine("JSON 返回" + res.Result.ToString());
        //#endif
        //                    return JsonConvert.DeserializeObject<HttpResult>(res.Result);
        //                });
        //            }
        //            else
        //            {
        //                // by wei,20200526 此处注释，因为发布后log.db 是明文存储接口地址 和 出参入参的记录，非常不安全，故发布版本注释掉此段代码
        //                //sdb.result = $"HttpStatusCode:{httpCode} Content:{ JsonConvert.SerializeObject(response.Result.Content)}";
        //                //LogHelper.AddSqliteDb(sdb);
        //                //Debug.WriteLine($"HttpStatusCode:{httpCode} Content:{JsonConvert.SerializeObject(response.Result.Content)}");
        //                // END BY WEI 20200526

        //                //return await Task.Run<HttpResult>(() => //原有4.5框架下的代码
        //                return await Task.Factory.StartNew<HttpResult>(() =>//4.0框架下支持的代码
        //                {
        //                    return new HttpResult()
        //                    {
        //                        status = "fail",
        //                        msg = $"接口异常:{httpCode}"
        //                    };
        //                });
        //            }
        //        }
        #endregion

        public static string GetResponse(string url)
        {
            string result = "";

            try
            {
                ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;// 防止 XP电脑上出现SSL 错误，bywei 20201211

                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Proxy = null;// 取消代理，将解决首次访问非常慢的问题
                req.Method = "GET";
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
                //req.ContentType = "application/html";

                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream stream = resp.GetResponseStream();
                //获取响应内容
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                return "";
            }
            //Console.WriteLine("Begin:" + url +":"+ DateTime.Now.ToString("HH:mm:ss ffff"));
            return result;
        }
        /// <summary>
        /// 调用接口通用方法
        /// </summary>
        /// <param name="url"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static HttpResult HttpService(string url, dynamic p)
        {
            YJTShiftManagement.Utils.SymmetricMethod symethod = new YJTShiftManagement.Utils.SymmetricMethod();

            string realurl = baseUrl + url;
            try
            {

                try
                {
                    if (false == IsConnected())
                    {
                        HttpResult hr = new HttpResult();
                        hr.status = "NetInterrupt";
                        hr.msg = "网络中断，请检查本地网络连接。请刷新网络连接，重新启动程序。";
                        hr.exception = new Exception("网络中断");
                        return hr;
                    }
                }
                catch (Exception ex)
                {
                    HttpResult hr = new HttpResult();
                    hr.status = "NetInterrupt";
                    hr.msg = "网络连接异常，请检查本地网络连接。请刷新网络连接，重新启动程序。";
                    hr.exception = ex;
                    return hr;
                }
                string result = "";
                ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;// 防止 XP电脑上出现SSL 错误，bywei 20201211
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(realurl);
                req.Proxy = null;// 取消代理，将解决首次访问非常慢的问题
                req.Method = "POST";
                req.ContentType = "application/json";
                if (!string.IsNullOrEmpty(GlobalApp.Manager_Id) && !string.IsNullOrEmpty(GlobalApp.Token))
                {
                    req.Headers.Add("tokenmanagerid", GlobalApp.Manager_Id);
                    req.Headers.Add("token", GlobalApp.Token);
                }
                #region 添加Post 参数
                string json = JsonConvert.SerializeObject(p);
                //增加一个字段，用于版本控制,by weiz 20210624
                if (json == "{}")
                {
                    json = json.Substring(0, json.Length - 1) + $"\"ver\":\"{YJTShiftManagement.Utils.Common.GetCurrentVersion()}\",\"software\":\"card\"}}";
                }
                else
                {
                    json = json.Substring(0, json.Length - 1) + $",\"ver\":\"{YJTShiftManagement.Utils.Common.GetCurrentVersion()}\",\"software\":\"YJTHealthyCard\"}}";
                }


                //Console.WriteLine(json);
                byte[] data = Encoding.UTF8.GetBytes(json);
                req.ContentLength = data.Length;
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }

                #endregion 添加Post 参数

                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream stream = resp.GetResponseStream();
                //获取响应内容
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }
#if DEBUG
                DebugFile.IfWrite($"<==============================Request_Begin==============================================> ");
                DebugFile.IfWrite($"URL:{realurl}");
                DebugFile.IfWrite($"Request:{json}");
                DebugFile.IfWrite($"Response:{result}");
                DebugFile.IfWrite($"<==============================Request_End==============================================> ");
#else
#endif


#if DEBUG
#endif
                Console.WriteLine($"URL:{realurl}");
                Console.WriteLine($"Request:{json}");
                Console.WriteLine($"Response:{result}");
                return JsonConvert.DeserializeObject<HttpResult>(result);

            }
            catch (Exception ex)
            {
#if DEBUG
                #region 异常日志
                DebugFile.IfWrite($"<==============================Exception_Begin==============================================> ");
                DebugFile.IfWrite($"Exception_URL:{realurl}");
                DebugFile.IfWrite($"Exception_Request:{JsonConvert.SerializeObject(p)}");
                DebugFile.IfWrite($"Exception_Message:{ex.Message}");
                DebugFile.IfWrite($"<==============================Exception_End==============================================> ");
                #endregion

                HttpResult hr = new HttpResult();
                hr.status = "EXEerror";
                hr.msg = "数据连接失败，请联系微信客服";
                hr.exception = ex;
                return hr;
            }
        }
        /// <summary>
        /// 表单形式提交调用接口通用方法
        /// </summary>
        /// <param name="url"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static HttpResult HttpServiceForm(string url, IDictionary<string, string> parameters)
        {

            string realurl = baseUrl + "/" + url;

#if DEBUG
#endif



            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(realurl);
            req.Proxy = null;// 取消代理，将解决首次访问非常慢的问题
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            //增加一个字段，用于版本控制,by weiz 20210624
            //parameters.Add("ver", YJTHealthyCard.Utils.Common.GetCurrentVersion());
            //parameters.Add("software", "YJTHealthyCard");

            #region 添加Post 参数

            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in parameters)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }

#if DEBUG
            Console.WriteLine(DateTime.Now.ToString("HH:mm:ss ffff") + "Begin:" + url + "======> " + builder.ToString());
#endif
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }

            #endregion 添加Post 参数

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
#if DEBUG
            Console.WriteLine(DateTime.Now.ToString("HH:mm:ss ffff") + "End  :" + realurl + "======> " + result);
#endif
            return JsonConvert.DeserializeObject<HttpResult>(result);
        }
        /// <summary>
        /// 只发送请求 不等待响应
        /// </summary>
        /// <param name="url"></param>
        /// <param name="p"></param>
        public static void HttpServiceNoResponse(string url, dynamic p)
        {
            YJTShiftManagement.Utils.SymmetricMethod symethod = new YJTShiftManagement.Utils.SymmetricMethod();

            string realurl = baseUrl + url;
            try
            {
#if DEBUG
                Console.WriteLine(realurl);
                //realurl = "http://192.168.1.131/his_dvp/" + url;
                //  realurl = "https://dvp.lianjieit.net/his_dvp/" + url;
#endif
                //Console.WriteLine("Begin:" + url +":"+ DateTime.Now.ToString("HH:mm:ss ffff"));
                string result = "";
                ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;// 防止 XP电脑上出现SSL 错误，bywei 20201211
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
                //if (Utils.OSHelper.IsWindowsXP)
                //{

                //}
                //else
                //{

                //}


                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(realurl);
                req.Proxy = null;// 取消代理，将解决首次访问非常慢的问题
                req.Method = "POST";
                req.ContentType = "application/json";

                #region 添加Post 参数
                string json = JsonConvert.SerializeObject(p);
                //增加一个字段，用于版本控制,by weiz 20210624
                if (json == "{}")
                {
                    json = json.Substring(0, json.Length - 1) + $"\"ver\":\"{YJTShiftManagement.Utils.Common.GetCurrentVersion()}\",\"software\":\"YJTHealthyCard\"}}";
                }
                else
                {
                    json = json.Substring(0, json.Length - 1) + $",\"ver\":\"{YJTShiftManagement.Utils.Common.GetCurrentVersion()}\",\"software\":\"YJTHealthyCard\"}}";
                }


                Console.WriteLine(json);
                byte[] data = Encoding.UTF8.GetBytes(json);
                req.ContentLength = data.Length;
                //req.BeginGetRequestStream(new AsyncCallback(Compleate),req)
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }

                #endregion 添加Post 参数

#if DEBUG
                DebugFile.IfWrite($"<==============================Request_Begin==============================================> ");
                DebugFile.IfWrite($"URL:{realurl}");
                DebugFile.IfWrite($"Request:{json}");
                DebugFile.IfWrite($"Response:{result}");
                DebugFile.IfWrite($"<==============================Request_End==============================================> ");
#else
                #region YY 20210728接口返回失败记录日志
                HttpResult res = JsonConvert.DeserializeObject<HttpResult>(result);
                if (res.status == "fail")
                {
                    DebugFile.IfWrite($"<==============================Fail_Begin==============================================> ");
                    DebugFile.IfWrite($"Fail_URL:{symethod.Encrypto(realurl)}");
                    DebugFile.IfWrite($"Fail_Request:{symethod.Encrypto(json)}");
                    DebugFile.IfWrite($"Fail_ReturnDate:{symethod.Encrypto(result)}");
                    DebugFile.IfWrite($"<==============================Fail_End==============================================> ");

                }
                #endregion
#endif


                //Console.WriteLine("End  :" + url + ":" + DateTime.Now.ToString("HH:mm:ss ffff"));
                // return JsonConvert.DeserializeObject<HttpResult>(result);

            }
#if DEBUG

#else
            catch (System.Net.WebException we)
            {
                throw new Exception("无法联网，请检查网络");
                //HttpResult hr = new HttpResult();
                //hr.status = "fail";
                //hr.msg = "无法联网，请检查网络";
                //return hr;
            }
#endif
            catch (Exception ex)
            {
#if DEBUG
                #region 异常日志
                DebugFile.IfWrite($"<==============================Exception_Begin==============================================> ");
                DebugFile.IfWrite($"Exception_URL:{realurl}");
                DebugFile.IfWrite($"Exception_Request:{JsonConvert.SerializeObject(p)}");
                DebugFile.IfWrite($"Exception_Message:{ex.Message}");
                DebugFile.IfWrite($"<==============================Exception_End==============================================> ");
                #endregion
#else
                #region 异常日志
                DebugFile.IfWriteError($"<==============================Exception_Begin==============================================> ");
                DebugFile.IfWriteError($"Exception_URL:{symethod.Encrypto(realurl)}");
                DebugFile.IfWriteError($"Exception_Request:{symethod.Encrypto(JsonConvert.SerializeObject(p))}");
                DebugFile.IfWriteError($"Exception_Message:{ex.Message}");
                DebugFile.IfWriteError($"<==============================Exception_End==============================================> ");
                #endregion
#endif
                //HttpResult hr = new HttpResult();
                //hr.status = "fail";
                //hr.msg = ex.Message;
                //return hr;
            }
        }

        private static void Compleate(IAsyncResult asyncResult)
        {
            try
            {
                //HttpWebRequest req = (asyncResult.AsyncState as HttpWebRequest);
                //HttpWebResponse res = req.EndGetResponse(asyncResult) as HttpWebResponse;
                //StreamReader reader = new StreamReader(res.GetResponseStream());

                //HttpResult res = JsonConvert.DeserializeObject<HttpResult>(result);
                //if (res.status == "fail")
                //{
                //    DebugFile.IfWrite($"<==============================Fail_Begin==============================================> ");
                //    DebugFile.IfWrite($"Fail_URL:{symethod.Encrypto(realurl)}");
                //    DebugFile.IfWrite($"Fail_Request:{symethod.Encrypto(json)}");
                //    DebugFile.IfWrite($"Fail_ReturnDate:{symethod.Encrypto(result)}");
                //    DebugFile.IfWrite($"<==============================Fail_End==============================================> ");

                //}

            }
            catch
            {

            }
        }


        /// <summary>
        /// 调用获取excel接口通用方法
        /// </summary>
        /// <param name="url"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static HttpResult HttpServiceExcel(string url, string filepath, dynamic p)
        {
            try
            {
                string realurl = baseUrl + url;

#if DEBUG
                //realurl = "http://192.168.1.131/his_dvp/" + url;
                //realurl = "https://dvp.lianjieit.net/his_dvp/" + url;
#endif
                //Console.WriteLine("Begin:" + url +":"+ DateTime.Now.ToString("HH:mm:ss ffff"));
                string result = "";
                ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;// 防止 XP电脑上出现SSL 错误，bywei 20201211

                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(realurl);
                req.Proxy = null;// 取消代理，将解决首次访问非常慢的问题
                req.Method = "POST";
                req.ContentType = "application/json";

                #region 添加Post 参数
                string json = JsonConvert.SerializeObject(p);
                Console.WriteLine(json);
                byte[] data = Encoding.UTF8.GetBytes(json);
                req.ContentLength = data.Length;
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }

                #endregion 添加Post 参数

                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream stream = resp.GetResponseStream();



                if (resp.ContentType.Contains("excel"))
                {
                    #region 下载 excel

                    if (System.IO.File.Exists(filepath))
                    {
                        System.IO.File.Delete(filepath);    //存在则删除
                    }
                    FileStream fs = new FileStream(filepath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);

                    byte[] bArr = new byte[1024];
                    int size = stream.Read(bArr, 0, (int)bArr.Length);
                    while (size > 0)
                    {
                        fs.Write(bArr, 0, size);
                        size = stream.Read(bArr, 0, (int)bArr.Length);
                    }
                    fs.Close();
                    stream.Close();
                    HttpResult hr = new HttpResult()
                    {
                        data = filepath,
                        msg = "",
                        status = "success",
                    };
                    return hr;
                    #endregion
                }
                else
                {
                    #region -- 出错json
                    //获取响应内容
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        result = reader.ReadToEnd();
                    }

#if DEBUG
                    //TRTC.Log.I($"URL:{realurl}");
                    //TRTC.Log.I($"Result:{json}");
#endif

                    Console.WriteLine("Result  :" + result);
                    Console.WriteLine("End  :" + url + ":" + DateTime.Now.ToString("HH:mm:ss ffff"));
                    return JsonConvert.DeserializeObject<HttpResult>(result);
                    #endregion
                }
            }
            catch (System.Net.WebException we)
            {
                throw new Exception("无法联网，请检查网络");
                //HttpResult hr = new HttpResult();
                //hr.status = "fail";
                //hr.msg = "无法联网，请检查网络";
                //return hr;
            }
            catch (Exception ex)
            {
                HttpResult hr = new HttpResult();
                hr.status = "fail";
                hr.msg = ex.Message;
                return hr;
            }
        }



        #region 网络是否连接

        #region 网络是否连接
        [System.Runtime.InteropServices.DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState(out int connectionDescription, int reservedValue);
        /// <summary>
        /// 网络是否连接
        /// </summary>
        /// <returns></returns>
        private static bool IsConnected()
        {
            try
            {
                int I = 0;
                bool state = InternetGetConnectedState(out I, 0);
                return state;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        #endregion 
        #endregion

    }
    public class HttpResult
    {
        public string status { get; set; }
        public string msg { get; set; }
        public object data { get; set; }
        public int count { get; set; } = 0;
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        [DefaultValue("")]
        public string sql { get; set; }
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        [DefaultValue("")]
        public string html_url { get; set; }

        /// <summary>
        /// 消息提示图片url 20211129 展示西药续方即将关闭提示使用
        /// </summary>
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        [DefaultValue("")]
        public string notice_img { get; set; }
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        [DefaultValue(null)]
        public Exception exception { get; set; }
    }
}
#endif